package jee.boot.common.utils.excel.template;


import jee.boot.common.utils.DateUtils;
import jee.boot.common.utils.Encodes;
import jee.boot.common.utils.StringUtils;
import jee.boot.common.utils.excel.excel.Function;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * 通过excel模板导出excel文件工具类
 * 架构不合理,将在下一个大版本中移除
 * @author zhilei.wang
 */
@Deprecated
public class ExportTemplateExcel {
    private byte[] b;//输出流byte
    private InputStream is;//输入模板流
    private Map<String, Object> data = new HashMap<>();//需要导出的数据
    /**
     * 设置导出的模板名称
     *
     * @param templateFileName
     * @return
     * @throws IOException
     */
    public ExportTemplateExcel templateFileName(String templateFileName) throws IOException {
        String pathName = "/templates/excel/" + templateFileName;
        Resource resource = new ClassPathResource(pathName);
        ByteArrayOutputStream bos = null;
		is = resource.getInputStream();
//        is = new FileInputStream("C:\\work\\idea-workspace\\java_framework\\backend\\jeeBoot\\business-center\\singleton-service\\src\\main\\resources\\templates\\excel\\" + templateFileName);
        return this;
    }

    /**
     * 设置导出的数据模型
     *
     * @param model
     * @return
     * @throws IOException
     */
    public ExportTemplateExcel templateExcelModel(ExportModel model) throws Exception {
        this.templateFileName("template.xlsx");
        // 解析excel中需要导出的
       // Map<String, Object> data = new HashMap<>();
        List<Map<String, Object>> exportFieldList = new ArrayList<>();
        if(!data.containsKey("title")){
            data.put("title", model.getTitle());
        }
		data.put("exportFieldList", exportFieldList);
        //data.put("foreachStart","<jx:forEach items=\"${list}\" var=\"entity\">");
        //data.put("foreachEnd","</jx:forEach>");
        List<? extends ExportField> fieldList = model.getExportFieldList();
        if (fieldList != null && !fieldList.isEmpty()) {
            for (ExportField ef : fieldList) {
                Map<String, Object> map = new HashMap<>();
                map.put("title", ef.getTitle());
                //如果是字典类型:${function.dic("del_flag", data.dictField)}
                if (StringUtils.isNotBlank(ef.getDictType())) {
                    map.put("fieldName", "${function.dic(\"" + ef.getDictType() + "\",entity." + ef.getFieldName() + ")}");
                } else {
                    if (StringUtils.isNotBlank(ef.getFormat())) {
                        // 如果是时间类型的格式化:${function.dateFormat(data.dateField1e, "yyyy-mm-dd")}
                        if (Date.class.equals(ef.getFieldType())) {
                            map.put("fieldName", "${function.dateFormat(entity." + ef.getFieldName() + ",\"" + ef.getFormat() + "\")}");
                        } else {// 数字类型格式化:${function.format(data.dateField1e, "0.00")}
                            map.put("fieldName", "${function.format(entity." + ef.getFieldName() + ",\"" + ef.getFormat() + "\")}");
                        }
                    } else {
                        map.put("fieldName", "${entity." + ef.getFieldName() + "}");
                    }
                }
                exportFieldList.add(map);
            }
        }
        return this;
    }
    /**
     * 设置导出的数据
     *
     * @param data
     * @return
     * @throws IOException
     */
    public ExportTemplateExcel templateData(Map<String,Object> data) throws IOException {
         this.data.putAll(data);
         return this;
    }
    /**
     * 构建excel文件
     *
     * @param templateFileName 模板文件名
     * @param data             构建excel使用的数据
     * @return
     * @throws Exception
     */
    public ExportTemplateExcel buildExcel(String templateFileName, Map<String, Object> data) throws Exception {
        this.templateFileName(templateFileName);
        this.data.putAll(data);
        // 适配自定义模板导出
        this.data.put("exportFieldList",new ArrayList<>());
        return buildExcel();
                }


    /**
     * 构建excel文件
     *
     * @return
     * @throws Exception
     */
    public ExportTemplateExcel buildExcel() throws Exception {
        ByteArrayOutputStream bos = null;
        try {
        	// 如果为定义导出列,使用默认的列属性作为导出列
        	initFieldListIfNotDef();
            data.put("function", new Function());
            // 关联模板
            XLSTransformer transformer = new XLSTransformer();
            Workbook workBook = transformer.transformXLS(is, data);
            bos = new ByteArrayOutputStream();
            workBook.write(bos);
            b = bos.toByteArray();
            return this;
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (null != bos) {
                    bos.close();
                }
            } catch (IOException e) {
                throw e;
            }
        }
    }

    /**
	 *  如果为定义导出列,使用默认的列属性作为导出列
     */
	private void initFieldListIfNotDef() throws Exception{
		if(!data.containsKey("exportFieldList")){
			if(data.containsKey("list")){
				List<Map<String,Object>> list=(List<Map<String,Object>>)data.get("list");
				if(!list.isEmpty()){
					List<DefaultExportField> fieldList=new ArrayList<>();
					DefaultExportModel model=new DefaultExportModel();
					model.setTitle("数据导出");
					model.setExportFieldList(fieldList);
					Map<String, Object> objectMap = list.get(0);
					for(Map.Entry<String,Object>entity:objectMap.entrySet()){
						String key = entity.getKey();
						DefaultExportField def=	new DefaultExportField();
						def.setFieldName(key);
						def.setTitle(key);
						fieldList.add(def);
                                }
					this.templateExcelModel(model);
                }

                            }
                        }

        }

    /**
     * 输出数据流
     *
     * @param os 输出数据流
     */
    public ExportTemplateExcel write(OutputStream os) throws IOException {
        os.write(b);
        return this;
    }

    /**
     * 输出到客户端
     *
     * @param fileName 输出文件名
     */
    public ExportTemplateExcel write(HttpServletResponse response, String fileName) throws IOException {
        return write(response, fileName, "xlsx");
    }

    public ExportTemplateExcel write(HttpServletResponse response, String fileName, String extName) throws IOException {
        String finalName = fileName + DateUtils.getDate("_yyyyMMddHHmmss") + "." + extName;
        response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + Encodes.urlEncode(finalName));
        write(response.getOutputStream());
        return this;
    }

    /**
     * 输出到文件
     *
     * @param fileName 输出文件名
     */
    public ExportTemplateExcel writeFile(String fileName) throws FileNotFoundException, IOException {
        FileOutputStream os = new FileOutputStream(fileName);
        this.write(os);
        return this;
    }

    /**
     * 清理临时数据
     */
    public ExportTemplateExcel dispose() {
        b = null;
        is = null;
        data.clear();
        return this;
    }
}
